/*
 * 我的任务列表
 */
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter_auth/constant/globals.dart' as globals;
import 'package:flutter_auth/common/service.dart';
import 'package:flutter_auth/common/picker_tool.dart';
import 'package:flutter_auth/constants.dart';
import 'package:loading_indicator/loading_indicator.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_styled_toast/flutter_styled_toast.dart';
import './editDetails/editDetails.dart'; // 我的任务详情
import './addDetails/addDetails.dart'; // 添加我的任务详情

class MyTask extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyTaskState();
}

class MyTaskState extends State<MyTask> with AutomaticKeepAliveClientMixin {
  bool get wantKeepAlive => true;
  SlidableController slidableController;
  var userInfo = globals.userInfo['data'];
  ScrollController _scrollController = new ScrollController();
  bool isPerformingRequest = false; // 是否加载中
  bool isAddMore = true; // 是否还有更多
  bool initLoading = true; // 初始化加载
  List<dynamic> dataSource = []; // 数据源
  int currentPage = 1;
  int pageSize = 15;
  String month = ''; // 当前选择的月份
  var activeItem = {}; // 当前滑动子模块
  @override
  void initState() {
    super.initState();
    getLogList(); // 获取用户日志列表
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        getLogList();
      }
    });
    slidableController = SlidableController(
      onSlideAnimationChanged: handleSlideAnimationChanged,
      onSlideIsOpenChanged: handleSlideIsOpenChanged,
    );
  }

  Animation<double> _rotationAnimation;
  Color _fabColor = Colors.blue;

  void handleSlideAnimationChanged(Animation<double> slideAnimation) {
    setState(() {
      _rotationAnimation = slideAnimation;
    });
  }

  void handleSlideIsOpenChanged(bool isOpen) {
    setState(() {
      _fabColor = isOpen ? Colors.green : Colors.blue;
    });
  }

  /*
   * 获取用户日志列表 
   */
  void getLogList() async {
    if (!isPerformingRequest && isAddMore == true) {
      setState(() => isPerformingRequest = true);
      Future.delayed(Duration(milliseconds: 400), () async {
        getLogSysList(); // 获取日志列表
      });
    }
  }

  /*
   * 获取日志列表 
   */
  void getLogSysList() async {
    // 获取个人日志列表
    List<dynamic> newList = await getLogListServer({
      'month': month,
      'order': 'DESC',
      'currentPage': currentPage,
      'pageSize': pageSize,
      'userId': userInfo['id']
    }).then((result) {
      if (result != null &&
          result['state'] == true &&
          result['data']['list'].length > 0) {
        return result['data']['list'];
      } else {
        return [];
      }
    });
    if (newList.length != pageSize) {
      setState(() {
        isAddMore = false;
      });
    }
    if (newList.length > 0) {
      if (dataSource.length > 0) {
        dataSource.removeAt(dataSource.length - 1);
      }
      setState(() {
        newList.add({});
        dataSource.addAll(newList);
        currentPage++;
      });
    }
    setState(() {
      isPerformingRequest = false;
      initLoading = false;
    });
  }

  /*
   * 添加加载标记
   */
  Widget _buildProgressIndicator() {
    return Container(
      padding: const EdgeInsets.all(16.0),
      alignment: Alignment.center,
      height: 80.0,
      child: LoadingIndicator(
        indicatorType: Indicator.ballRotateChase,
        color: kPrimaryColor,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('我的任务'),
        leading: IconButton(
          icon: Icon(Icons.history),
          onPressed: () {
            PickerTool.showDatePicker(
              context,
              dateType: DateType.YM,
              title: "月份",
              value: month != ''
                  ? DateTime.parse("$month-01")
                  : new DateTime.now(),
              clickCallback: (var str, var time) {
                setState(() {
                  month = str;
                  initLoading = true;
                  isAddMore = true;
                  currentPage = 1;
                  dataSource = [];
                });
                getLogSysList(); // 获取日志列表
              },
            );
          },
        ),
        actions: _isClearMonth(),
      ),
      body: _buildSuggestions(),
    );
  }

  /*
   * 根据月份的选择状态展示不同的widget 
   */
  List<Widget> _isClearMonth() {
    List<Widget> actions = [];
    if (month != '') {
      actions = [
        IconButton(
          icon: Icon(Icons.clear),
          onPressed: () {
            setState(() {
              month = '';
              initLoading = true;
              isAddMore = true;
              currentPage = 1;
              dataSource = [];
            });
            getLogSysList(); // 获取日志列表
          },
        ),
        IconButton(
          icon: Icon(Icons.add_box),
          onPressed: () {
            Navigator.push(context, MaterialPageRoute(builder: (context) {
              return AddDetails();
            }));
          },
        )
      ];
    } else {
      actions = [
        IconButton(
          icon: Icon(Icons.add_box),
          onPressed: () {
            Navigator.push(context, MaterialPageRoute(builder: (context) {
              return AddDetails();
            })).then((result) {
              if (result == true) {
                setState(() {
                  month = '';
                  initLoading = true;
                  isAddMore = true;
                  currentPage = 1;
                  dataSource = [];
                });
                getLogSysList(); // 获取日志列表
              }
            });
          },
        )
      ];
    }
    return actions;
  }

  /*
   * 展示视图
   */
  Widget _buildSuggestions() {
    if (initLoading == true) {
      return Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(160.0),
        child: LoadingIndicator(
          indicatorType: Indicator.ballRotateChase,
          color: kPrimaryColor,
        ),
      );
    } else if (dataSource.length > 0) {
      return Scrollbar(
        child: ListView.separated(
          itemCount: dataSource.length,
          controller: _scrollController,
          //列表项构造器
          itemBuilder: (BuildContext context, int index) {
            final Axis slidableDirection = Axis.horizontal;
            if (index == dataSource.length - 1) {
              if (isAddMore == false) {
                return Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.all(16.0),
                  child: Text(
                    "没有更多了",
                    style: TextStyle(color: Colors.grey),
                  ),
                );
              } else {
                return _buildProgressIndicator(); // 添加加载标记
              }
            }
            return _getSlidableWithLists(context, index, slidableDirection);
          },
          //分割器构造器
          separatorBuilder: (context, index) => Divider(height: 10.0),
        ),
      );
    } else {
      return Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(16.0),
        child: Text(
          "暂无数据",
          style: TextStyle(
            color: Colors.grey,
            fontSize: 20,
          ),
        ),
      );
    }
  }

  /*
   * 展示列表（可左右删除的列表）
   */
  Widget _getSlidableWithLists(
      BuildContext context, int index, Axis direction) {
    var item = dataSource[index];
    var projectName = dataSource[index]['list'].length > 0
        ? dataSource[index]['list'][0]['projectName']
        : '无';
    /*
    * 列表展示
    */
    List<Widget> _listTileColumn(var item) {
      List<Widget> list = [];
      if (item['trueDate'] != '') {
        list.add(Text("${item['trueDate']}"));
      }
      if (item['userName'] != '') {
        list.add(Text("${item['userName']}"));
      }
      if (item['jobsSuggest'] != '') {
        list.add(Text(
          "${item['jobsSuggest']}",
          softWrap: true,
          maxLines: 3,
          overflow: TextOverflow.ellipsis,
        ));
      }
      if (item['difficultHelp'] != '') {
        list.add(Text(
          "${item['difficultHelp']}",
          softWrap: true,
          maxLines: 3,
          overflow: TextOverflow.ellipsis,
        ));
      }
      return list;
    }

    /*
     * 点击跳转编辑页面
     */
    void _navigatorToEdit() {
      item['index'] = index;
      Navigator.push(context, MaterialPageRoute(builder: (context) {
        return EditDetails(value: item);
      })).then((data) {
        if (data != null) {
          getLogByLogId({'userId': data['userId'], 'logId': data['logId']})
              .then((result) {
            if (result["state"]) {
              setState(() {
                int index = data['index'];
                result['data']['logId'] = data['logId'];
                dataSource[index] = result['data'];
              });
            }
          });
        }
      });
    }

    return RawGestureDetector(
      gestures: {
        // 建立多手势识别器与手势识别工厂类的映射关系，从而返回可以响应该手势的recognizer
        MultipleDragGestureRecognizer:
            GestureRecognizerFactoryWithHandlers<MultipleDragGestureRecognizer>(
          () => MultipleDragGestureRecognizer(),
          (MultipleDragGestureRecognizer instance) {
            instance.onEnd = (DragEndDetails details) {
              if (details.velocity.pixelsPerSecond.dx > 0) {
                if (activeItem['id'] != null &&
                    activeItem['id'] == item['id']) {
                  activeItem = {};
                  slidableController.activeState = null;
                }
              } else if (details.velocity.pixelsPerSecond.dx < 0) {
                activeItem = item;
              }
            };
          },
        )
      },
      child: Slidable(
        key: Key(item['id'].toString()),
        direction: direction,
        controller: slidableController,
        actionExtentRatio: 0.25,
        actionPane: SlidableDrawerActionPane(),
        child: ListTile(
          title: Text("${item['date']}"),
          subtitle: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: _listTileColumn(item),
          ),
          onTap: () {
            if (activeItem['id'] != null) {
              if (activeItem['id'] != item['id']) {
                if (slidableController.activeState != null) {
                  slidableController.activeState = null;
                }
                new Future.delayed(const Duration(milliseconds: 200), () {
                  _navigatorToEdit(); // 点击跳转编辑页面
                  activeItem = {};
                });
              } else {
                if (slidableController.activeState != null) {
                  slidableController.activeState = null;
                } else {
                  _navigatorToEdit(); // 点击跳转编辑页面
                  activeItem = {};
                }
              }
            } else {
              if (slidableController.activeState != null) {
                slidableController.activeState = null;
              } else {
                _navigatorToEdit(); // 点击跳转编辑页面
                activeItem = {};
              }
            }
          },
          trailing: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Text('$projectName'),
              Icon(Icons.chevron_right),
            ],
          ),
        ),
        secondaryActions: <Widget>[
          IconSlideAction(
            caption: '删除',
            color: Colors.red,
            icon: Icons.delete,
            onTap: () async {
              bool delete = await showDeleteConfirmDialog(); // 弹出删除确认框
              if (delete == null) {
                print("取消删除");
              } else {
                deleteItem(context, '删除成功', index);
              }
            },
          ),
        ],
      ),
    );
  }

  /*
   * 删除子集 
   */
  void deleteItem(BuildContext context, String text, index) {
    var item = dataSource[index];
    deleteLogByLogIdAndUserId({'logId': item['id'], 'userId': userInfo['id']})
        .then((result) {
      showToast(
        result['msg'],
        context: context,
        animation: StyledToastAnimation.slideFromBottom,
        reverseAnimation: StyledToastAnimation.slideToBottom,
        startOffset: Offset(0.0, 3.0),
        reverseEndOffset: Offset(0.0, 3.0),
        position: StyledToastPosition.bottom,
        duration: Duration(seconds: 4),
        animDuration: Duration(seconds: 1),
        curve: Curves.elasticOut,
        reverseCurve: Curves.fastOutSlowIn,
      );
      setState(() {
        dataSource.removeAt(index);
      });
    });
  }

  /*
   * 弹出删除确认框 
   */
  Future<bool> showDeleteConfirmDialog() {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("提示"),
          content: Text("您确定要删除?"),
          actions: <Widget>[
            FlatButton(
              child: Text("取消"),
              onPressed: () => Navigator.of(context).pop(), // 关闭对话框
            ),
            FlatButton(
              child: Text("删除"),
              onPressed: () {
                //关闭对话框并返回true
                Navigator.of(context).pop(true);
              },
            ),
          ],
        );
      },
    );
  }
}

class MultipleDragGestureRecognizer extends HorizontalDragGestureRecognizer {
  @override
  void rejectGesture(int pointer) {
    acceptGesture(pointer);
  }
}
